package cn.edu.mju.dilidili.auth.controller;

import cn.edu.mju.dilidili.common.utils.ConnectUtil;
import cn.edu.mju.dilidili.common.utils.Result;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class CaptchaController {

    final RedisTemplate<String, String> redis;

    @GetMapping("/captcha")
    Result<String> captcha() {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 40);
        String session = ConnectUtil.getSessionId();
        redis.opsForValue().set(session, captcha.getCode(), 6000, TimeUnit.SECONDS);
        return new Result<>(captcha.getImageBase64Data());
    }

    @GetMapping("/getCaptcha")
    Result<String> getCaptcha() {
        return new Result<>(redis.opsForValue().get(ConnectUtil.getSessionId()));
    }
}
